import Vue from 'vue';

/**
* 防抖函数
* @param func 用户传入的防抖函数
* @param wait 等待的时间
* @param immediate 是否立即执行
*/
export const debounce = (func, wait = 50, immediate = false) => {
  // 缓存一个定时器id
  let timer = null;
  let result;
  const debounced = function(...args) {
    // 如果已经设定过定时器了就清空上一次的定时器
    if (timer) {
      clearTimeout(timer);
    }
    if (immediate) {
      const callNow = !timer;
      // 等待wait的时间间隔后，timer为null的时候，函数才可以继续执行
      timer = setTimeout(() => {
        timer = null;
      }, wait);
      // 未执行过，执行
      if (callNow) result = func.apply(this, args);
    } else {
      // 开始一个定时器，延迟执行用户传入的方法
      timer = setTimeout(() => {
        // 将实际的this和参数传入用户实际调用的函数
        func.apply(this, args);
      }, wait);
    }
    return result;
  }
  debounced.cancel = function() {
    clearTimeout(timer);
    timer = null;
  }
  // 这里返回的函数时每次用户实际调用的防抖函数
  return debounced;
}

export function ssoPermission(urlpath, title,token) {
  var xhr = new XMLHttpRequest()
  var formData = new FormData()
  xhr.open('get', urlpath)
  xhr.setRequestHeader('Authorization', `bearer ${token}`)
  xhr.responseType = 'blob'
  xhr.onload = function(e) {
    const blob = new Blob([xhr.response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
    const downloadElement = document.createElement('a')
    const href = window.URL.createObjectURL(blob) // 创建下载的链接
    downloadElement.href = href
    downloadElement.download = title + '.xlsx' // 下载后文件名
    document.body.appendChild(downloadElement)
    downloadElement.click() // 点击下载
    document.body.removeChild(downloadElement) // 下载完成移除元素
    window.URL.revokeObjectURL(href) // 释放掉blob对象
  }
  xhr.send(formData)
}

export function postPermission(urlpath, title, excdata,token) {
  var xhr = new XMLHttpRequest()
  var formData = new FormData()
  xhr.open('post', urlpath)
  xhr.setRequestHeader('Content-Type', 'application/json')
  xhr.setRequestHeader('Authorization', `bearer ${token}`)
  xhr.responseType = 'blob'
  xhr.onload = function(e) {
    const blob = new Blob([xhr.response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
    const downloadElement = document.createElement('a')
    const href = window.URL.createObjectURL(blob) // 创建下载的链接
    downloadElement.href = href
    downloadElement.download = title + '.xlsx' // 下载后文件名
    document.body.appendChild(downloadElement)
    downloadElement.click() // 点击下载
    document.body.removeChild(downloadElement) // 下载完成移除元素
    window.URL.revokeObjectURL(href) // 释放掉blob对象
  }
  xhr.send(excdata)
}

/*
 * 导出Excel
 */
export function exportExcel(headers, fields, list, filename, autoWidth, bookType) {
  import('@/vendor/Export2Excel').then(excel => {
    let data = [];
    if (fields && fields.length) {
      data = formatJson(fields, list);
    } else {
      data = list;
    }
    excel.export_json_to_excel({
      header: headers,
      data,
      filename: filename,
      autoWidth: autoWidth ? autoWidth : true,
      bookType: bookType
    });
  });
}
export function formatJson(filterVal, jsonData) {
  return jsonData.map(v => filterVal.map(j => v[j]));
}
